<template>
    <baseInfo :info="info">
        <template #test1>
          <el-form-item label="项目名称">
            <el-select v-model="form.xmid" placeholder="请选择项目名称" size="medium" filterable style="width:100%;" @change="getProjectBaseInfo">
              <el-option :label="v.name" :value="v.id" v-for="(v,i) in ysList" :key="i"></el-option>
            </el-select>
          </el-form-item>
        </template>

        <template v-slot:test2>
          <el-row>
            <el-col :span="6" >
              <el-form-item label="立项金额">
                <el-input v-model="info.offer" placeholder="立项金额" disabled ></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6" >
              <el-form-item label="预算金额">
                <el-input v-model="form.ysmoney" placeholder="预算金额" @blur="changeMoney()"></el-input>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="预算成本">
                <el-input v-model="form.yscost" placeholder="预算成本" disabled></el-input>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="6">
              <el-form-item label="货币币种">
                <el-input v-model="info.currency" placeholder="货币币种"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
      <!--预算明细-->
          <fieldset style="border:1px #e6e6e6 solid;width:67.5%;margin-left: 4%;">
            <legend style="text-align: center;font-size:24px">预算明细</legend>
        <el-form-item>
         <el-row type="flex" justify="center">
           <el-col :span="7" style="border:1px #e6e6e6 solid;text-align: center;">标题</el-col>
           <el-col :span="7" style="border:1px #e6e6e6 solid;text-align: center;">金额</el-col>
           <el-col :span="7" style="border:1px #e6e6e6 solid;text-align: center;">备注</el-col>
<!--           <el-col :span="3" style="border:1px #e6e6e6 solid;text-align: center;">操作</el-col>-->
           <el-col :span="3"></el-col>
         </el-row>
          <el-row type="flex" justify="center" v-for="(vv,k) in ysData" :key="k" :gutter="5" class="mt5">
            <el-col :span="7"><el-input v-model="vv.title" placeholder="输入标题" @blur="checkTitle(k)"></el-input></el-col>
            <el-col :span="7"><el-input v-model="vv.money" placeholder="输入金额" @blur="calculateProfit(k)" @focus="hiddenMoney(vv.money,k)"></el-input></el-col>
            <el-col :span="7"><el-input v-model="vv.desc" @focus="handleFocus(vv)" placeholder="输入备注"></el-input></el-col>
            <el-col :span="3"><el-button type="danger" v-if="vv.isDel" @click="delYsData(k)" size="mini">删除</el-button></el-col>
<!--            <el-col :span="3"></el-col>-->
          </el-row>
          <el-row type="flex" justify="center" align="middle" class="mt5">
            <el-col :span="12"><el-button type="primary" @click="addYsData">添加预算</el-button></el-col>
          </el-row>
          <div style="margin-top:20px;">
            <el-row type="flex" justify="center">
              <el-col :span="7" style="border:1px #e6e6e6 solid;text-align: center;">标题</el-col>
              <el-col :span="7" style="border:1px #e6e6e6 solid;text-align: center;">金额</el-col>
              <el-col :span="7" style="border:1px #e6e6e6 solid;text-align: center;">备注</el-col>
<!--              <el-col :span="3" style="opacity: 0">操作</el-col>-->
              <el-col :span="3"></el-col>
            </el-row>
            <el-row type="flex" justify="center" v-for="(vv,k) in ysData2" :key="k" :gutter="5" class="mt5">
              <el-col :span="7"><el-input v-model="vv.title" placeholder="输入标题" disabled></el-input></el-col>
              <el-col :span="7"><el-input v-model="form[vv.font_price]" placeholder="输入金额" disabled></el-input></el-col>
              <el-col :span="7"><el-input v-model="vv.desc" @focus="handleFocus(vv)" placeholder="输入备注" disabled></el-input></el-col>
              <el-col :span="3"></el-col>
            </el-row>
          </div>

        </el-form-item>
          </fieldset>
      <!--预算明细-->

<!--      上传附件-->
        <el-form-item style="text-align: left !important;" label="附件">
<!--          <uploadFile :fileList="fileList" :params="params" @test="changeFileList"></uploadFile>-->
          <MyUploadFile
          dir="project_ys"
          :files="fileList"
          @receiveFile="changeFileList"
          ref="ysUpload"
          >
          </MyUploadFile>
        </el-form-item>
      <!--文件上传-->

      <el-form-item label="备注">
        <el-input type="textarea" v-model="form.desc"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit(0)">提交</el-button>
        <el-button type="primary" @click="onSubmit(1)">保存</el-button>
        <el-button @click="resetFormData">取消</el-button>
      </el-form-item>

        </template>
    </baseInfo>

</template>

<script>
import uploadFile from "../common/uploadFile";
import {getYsList,getProjectBase,addProjectYs, calculateProfitApi} from '@/apilist/Project';
import baseInfo from "../common/baseInfo";
import MyUploadFile from "../common/MyUploadFile.vue";

export default {
name: "project_ys",
  data() {
    return {
        fileList: [],
        params:{dir:'project_ys'},
        ysList: [],//预算下拉
        info:{
            name:'',
            partner_id: '',
            company: '',
            dept: '',
            start: '',
            stop: '',
            leader:'',
            leader_mobile: '',
            customer: '',
            customer_mobile: '',
            seller: '',
            seller_mobile: '',
            currency: 'CNY',
            offer: '',
            cost: '',
            city: '',
            ys_offer: '0.00',
            ys_cost: '0.00',
        },
        form: {
            xmid: '',
            tax:0.0,
            sub_total: 0,
            total: 0,
            percent: 0,
            profit: 0,
            ysmoney: 0,
            yscost: 0,
            city: '',
            ysid: 0,
        },
        ysData:[
            {title: '押金',money: 0,desc: '默认',isDel: false,paytype:7,id: 0},
            {title: '差旅',money: 0,desc: '默认',isDel: false,paytype:1,id: 0},
            {title: '采买',money: 0,desc: '默认',isDel: false,paytype:2,id: 0},
            {title: '借款',money: 0,desc: '默认',isDel: false,paytype:6,id: 0},
            {title: '临款',money: 0,desc: '默认',isDel: false,paytype:9,id: 0},
        ],
        ysData2:[
        {title: '合计金额',font_price:'sub_total',desc: '默认'},
        {title: '税费金额',font_price:'tax',desc: '默认'},
        {title:'总计金额',font_price:'total',desc: '默认'},
        {title: '利润金额',font_price:'profit',desc: '默认'},
        {title: '利润率(%)',font_price:'percent',desc: '默认'},
      ],
        newYs: {title: '',money: 0,desc: '',isDel: true,paytype:4,id: 0},
        isSubmit: true,
    };
  },
  methods: {
    handleFocus(item){
      if(item.desc ==='默认'){
        item.desc = ''
      }
    },
      //提交预算
      onSubmit(is_save){
          if(!this.isSubmit) return;
          this.isSubmit = false;
          try {
            if (!is_save && this.form.desc === '') throw new Error("备注不能为空")
              this.form.is_save = is_save
            this.form.ysData = this.ysData
            this.form.fileList = this.$refs.ysUpload.getNewFileList()
            this.form.city = this.info.city
            this.form.currency = this.info.currency
            addProjectYs(this.form).then(res => {
              if (res.state == 'err')  throw new Error(res.msg)
              this.$message({
                type: 'success',
                message: res.msg,
                onClose: () => {
                  this.$router.push({
                    path: '/project_list',
                    query: {tab: 1}
                  });
                }
              });
            }).catch((err)=>{
              this.$message.error(err.message);
              this.isSubmit = true;
            })
          }catch (e){
            console.log(e)
            this.isSubmit = true;
            this.$message.error(e.message);
            return false;
          }
      },
    //重置数据
    resetFormData(){
      this.fun.resetFormData(this.info);
      this.fun.resetFormData(this.form);
      this.ysData = [
        {title: '押金',money: 0,desc: '默认',isDel: false,paytype:7,id: 0},
        {title: '差旅',money: 0,desc: '默认',isDel: false,paytype:1,id: 0},
        {title: '采买',money: 0,desc: '默认',isDel: false,paytype:2,id: 0},
        {title: '借款',money: 0,desc: '默认',isDel: false,paytype:6,id: 0},
        {title: '临款',money: 0,desc: '默认',isDel: false,paytype:9,id: 0},
      ];
    },



      //修改金额
      changeMoney(){
        let money = this.fun.resetMoney(this.form.ysmoney)
        let tax =  money * this.info.rate
        this.form.tax = this.fun.fmoney(tax)
        this.calculateProfit(0)
      },

      addYsData()
      {
          let newYs = {title: '',money: 0,desc: '',isDel: true,paytype:4}
          this.ysData.push(newYs)

      },
      delYsData(i){
        this.$confirm('是否删除预算?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          this.ysData.splice(i,1)
          let k = this.ysData.length - 1
          this.calculateProfit(k)
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });
      },

      //计算利润
      calculateProfit(i)
      {
          let money = this.ysData[i].money
          money = this.fun.resetMoney(money)
          this.ysData[i].money = this.fun.fmoney(money,2)
          if(this.fun.isNull(this.form.tax)) {
            this.$message.error('请选择项目');
            return ;
          }
          calculateProfitApi({
            offer: this.form.ysmoney,
            rate: this.info.rate,
            ysData: this.ysData,
          }).then(res => {
            this.form.sub_total = res.data.sub_total;
            this.form.yscost = res.data.cost;
            this.form.total = res.data.total;
            this.form.percent = res.data.percent;
            this.form.profit = res.data.profit;
            this.form.tax = res.data.tax;
            this.form.ysmoney = res.data.ysmoney
          });
      },
      //获取项目基本信息
      getProjectBaseInfo(){
          getProjectBase({id: this.form.xmid}).then(res => {
              this.info = res.data
              this.form.tax = res.data.tax
              this.form.ysmoney = res.data.ys_offer
              this.form.yscost = res.data.ys_cost

          })
      },
      //修改附件
      changeFileList(file){
          this.fileList.push(file)
      },
    hiddenMoney(money,k){
      this.ysData.forEach((item,i) =>{
        if(!money && k === i){
          this.ysData[i]['money'] = ''
        }
      })
    },
    //检查标题
    checkTitle(i){
      const title = this.ysData[i]['title']
      console.log("title", title)
      this.ysData.forEach((v,k)=>{
        if(k !== i && v['title'] == title){
          this.$message.error("预算"+title + "重复,请检查");
          return false;
        }
      });
    },

  },
    components:{uploadFile,baseInfo,MyUploadFile},
    //初始化
    created() {
        getYsList({}).then(res => {
            this.ysList = res.data
        })
    }

}
</script>

<style scoped>
.center-box{
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}
.mt5{margin-top: 5px;}
.tr{text-align: right;padding-right: 20px;}
</style>
